package br.com.winesys.geta.base;

import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Toolkit;
import javax.swing.JOptionPane;

public final class ExceptionMessage {

	private ExceptionMessage(){
		
	}
	
	public static String getMessage(String message, Throwable ex) {
		String exceptionMessage = ExceptionMessage.getMessage(ex);
		if (exceptionMessage.isEmpty()){
			return message; 
		}
		return message + ", causado por\n\t" + exceptionMessage;
	}

	public static String getMessage(Throwable ex) {
		if (ex == null) {
			return "";
		}
		final StringBuilder buffer = new StringBuilder();
		buffer.append(ex.getClass().getSimpleName());
		buffer.append(": ");
		buffer.append(ex.getMessage());
		while (ex.getCause() != null && !ex.getCause().equals(ex)) {
			ex = ex.getCause();
			buffer.append(", causado por\n\t");
			buffer.append(ex.getClass().getSimpleName());
			buffer.append(": ");
			buffer.append(ex.getMessage());
		}
		return buffer.toString();
	}

	public static void showMessage(final Component parent, final String message, final Throwable throwable) {
		if (EventQueue.isDispatchThread()) {
			Toolkit.getDefaultToolkit().beep();
			JOptionPane.showMessageDialog(parent, ExceptionMessage.getMessage(message, throwable), "ERRO", JOptionPane.ERROR_MESSAGE);
		} else {
			try {
				EventQueue.invokeAndWait(new Runnable() {
					@Override
					public void run() {
						ExceptionMessage.showMessage(parent, message, throwable);
					}
				});
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}

	public static void showMessage(final Component parent, final Throwable throwable) {
		if (EventQueue.isDispatchThread()) {
			Toolkit.getDefaultToolkit().beep();
			JOptionPane.showMessageDialog(parent, ExceptionMessage.getMessage(throwable), "ERRO", JOptionPane.ERROR_MESSAGE);
		} else {
			try {
				EventQueue.invokeAndWait(new Runnable() {

					@Override
					public void run() {
						ExceptionMessage.showMessage(parent, throwable);
					}
				});
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}
}